<template>
  <div class="login-container">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      autocomplete="on"
    >
      <div class="title-container">
        <h3 class="title">中药养生平台管理系统</h3>
      </div>

      <el-form-item prop="account">
        <el-input
          v-model="loginForm.account"
          placeholder="请输入账号"
          type="text"
          tabindex="1"
          autocomplete="on"
          prefix-icon="User"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="请输入密码"
          :type="passwordType"
          tabindex="2"
          autocomplete="on"
          prefix-icon="Lock"
          @keyup.enter="handleLogin"
        >
          <template #suffix>
            <el-icon class="show-pwd" @click="showPwd">
              <component :is="passwordType === 'password' ? 'Hide' : 'View'" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        class="login-button"
        @click="handleLogin"
      >
        登录
      </el-button>

      <div class="tips">
        <span>默认用户名: admin</span>
        <span>默认密码: admin123</span>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock, View, Hide } from "@element-plus/icons-vue";
import { login_API } from "@/api/user";
import { validUsername } from "@/utils/validate";

const router = useRouter();

const loginFormRef = ref(null);
const loading = ref(false);
const passwordType = ref("password");

const loginForm = reactive({
  account: "admin",
  password: "admin123",
});

const loginRules = {
  account: [
    { required: true, trigger: "blur", message: "请输入账号" },
    { validator: validateUsername, trigger: "blur" },
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入密码" },
    {
      min: 6,
      max: 20,
      message: "密码长度必须在6-20个字符之间",
      trigger: "blur",
    },
  ],
};

function validateUsername(rule, value, callback) {
  if (!validUsername(value)) {
    callback(new Error("请输入正确的用户名"));
  } else {
    callback();
  }
}

const showPwd = () => {
  passwordType.value = passwordType.value === "password" ? "" : "password";
};

const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 实际项目中这里应该调用真实的接口
        const { data } = await login_API(loginForm);
        localStorage.setItem("token", data.token);

        // 模拟登录成功
        localStorage.setItem("token", "admin-token-example");
        localStorage.setItem(
          "userInfo",
          JSON.stringify({
            id: "1",
            account: loginForm.account,
            role: "admin",
            avatar: "",
          })
        );

        ElMessage({
          message: "登录成功",
          type: "success",
          duration: 2000,
        });

        router.push({ path: "/" });
      } catch (error) {
        console.error("Login error:", error);
        ElMessage({
          message: error.message || "登录失败，请重试",
          type: "error",
          duration: 5 * 1000,
        });
      } finally {
        loading.value = false;
      }
    } else {
      ElMessage({
        message: "请输入正确的用户名和密码",
        type: "error",
      });
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
$bg: #283443;
$light_gray: #eee;
$cursor: #fff;

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #2d3a4b;

  .login-form {
    width: 400px;
    max-width: 100%;
    padding: 35px 35px 15px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);

    .title-container {
      position: relative;
      margin-bottom: 30px;

      .title {
        font-size: 26px;
        color: #333;
        margin: 0 auto 40px;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      cursor: pointer;
    }

    .login-button {
      width: 100%;
      margin-bottom: 30px;
    }

    .tips {
      font-size: 14px;
      color: #999;
      margin-top: 20px;
      text-align: center;

      span {
        margin-right: 20px;
      }
    }
  }
}

@media (max-width: 768px) {
  .login-container {
    .login-form {
      width: 90%;
      padding: 20px;
    }
  }
}
</style>
